package com.fintech.pangu.security.web;

import com.alibaba.fastjson.JSON;
import com.fintech.pangu.commons.api.BaseResponse;
import com.fintech.pangu.commons.enums.BusinessEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 需要登录认证的EntryPoint，json返回
 */
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(BaseResponse.failure(BusinessEnum.UN_AUTHORIZED_ERROR)));
        out.flush();
        out.close();
    }

}
